package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 根据用户id 或 设备id查询对应的行为实体 **(优先使用userId)**
     * @param userId  用户id
     * @param equipmentId  设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        /**
         *  1. 判断userId是否为空
         *  2. 判断设备id是否为空
         *  3. 如果userId和设备id都不存在  返回null 调用者需要判断null
         */
        if (userId != null) {
            Query query = Query.query(Criteria.where("refId").is(userId));
            ApBehaviorEntry entry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (entry == null) {
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setCreatedTime(new Date());
                apBehaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                apBehaviorEntry.setRefId(userId);
                mongoTemplate.save(apBehaviorEntry);
                return apBehaviorEntry;
            }
            return entry;
        }
        if (equipmentId != null) {
            Query query = Query.query(Criteria.where("equipmentId").is(equipmentId));
            ApBehaviorEntry entry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (entry == null) {
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setCreatedTime(new Date());
                apBehaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                mongoTemplate.save(apBehaviorEntry);
                return apBehaviorEntry;
            }
            return entry;
        }
        return null;
    }
}
